package logger

import (
	"os"
	"path/filepath"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

// Logger 应用日志记录器
var Logger *zap.Logger

func init() {
	// 初始化日志记录器
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{"stdout"}
	config.ErrorOutputPaths = []string{"stdout"}
	Logger = Init(&config)
}

// Init 初始化日志系统
func Init(config *zap.Config) *zap.Logger {
	var core zapcore.Core

	// 创建控制台输出
	consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
	consoleCore := zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), config.Level)

	if config.OutputPaths[0] != "stdout" {
		// 创建文件输出
		fileEncoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
		fileWriter := zapcore.AddSync(&lumberjack.Logger{
			Filename:   filepath.Join(config.OutputPaths[0], "app.log"),
			MaxSize:    100, // MB
			MaxBackups: 3,
			MaxAge:     30, // days
			Compress:   true,
		})
		fileCore := zapcore.NewCore(fileEncoder, fileWriter, config.Level)

		// 组合多个输出
		core = zapcore.NewTee(consoleCore, fileCore)
	} else {
		core = consoleCore
	}

	// 创建记录器
	Logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	return Logger
}

// 包装zap方法用于简化调用
func Info(msg string, fields ...zap.Field) {
	Logger.Info(msg, fields...)
}

func Warn(msg string, fields ...zap.Field) {
	Logger.Warn(msg, fields...)
}

func Error(msg string, fields ...zap.Field) {
	Logger.Error(msg, fields...)
}

func Fatal(msg string, fields ...zap.Field) {
	Logger.Fatal(msg, fields...)
}

func Sync() {
	_ = Logger.Sync()
}

// 创建Logger实例
func NewProductionLogger(path string) *zap.Logger {
	config := zap.NewProductionConfig()
	config.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
	config.OutputPaths = []string{path}
	config.ErrorOutputPaths = []string{path}
	return Init(&config)
}

func NewDevelopmentLogger(path string) *zap.Logger {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{path}
	config.ErrorOutputPaths = []string{path}
	return Init(&config)
}
